<template>
  <div class='app-container calendar-list-container'>
    <div class='filter-container'>
      <el-select v-model="listQuery.restId" placeholder="选择食堂">
        <el-option
          v-for="item in rests"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
      <el-date-picker id='dp' v-model='dailySech' type="daterange" @change="dailySechChange"
        align="right"
        placeholder="选择日期范围"
        :picker-options="pickerOptions2">
      </el-date-picker>
      <el-select v-model='listQuery.section' placeholder='餐次'>
        <el-option label="午餐" value="2"></el-option>
        <el-option label="晚餐" value="3"></el-option>
      </el-select>
      <el-select v-model='listQuery.payStatus' placeholder='支付状态'>
        <el-option label="已支付" value="1"></el-option>
        <el-option label="未支付" value="0"></el-option>
      </el-select>
      <el-select v-model='listQuery.enable' placeholder='订单状态' multiple>
        <el-option label="未接收" value="0"></el-option>
        <el-option label="已接收" value="10"></el-option>
        <el-option label="配送中" value="20"></el-option>
        <el-option label="已配送" value="30"></el-option>
        <el-option label="已完成" value="40"></el-option>
      </el-select>
      
      <el-button class='filter-item' type='primary' v-waves icon='search' @click='handleFilter'>明细</el-button>
      <el-button class='filter-item' type='primary' v-waves icon='search' @click='handleCollect'>汇总</el-button>
      <el-button class="filter-item" type="primary" icon="document" @click="handleDownload">导出</el-button>
      <el-checkbox class="filter-item" @change='tableKey=tableKey+1' v-model="showAuditor">显示详细</el-checkbox>
    </div>
    <el-table height="400" @selection-change="selsChange" :key='tableKey' :data='list' v-loading='listLoading' element-loading-text='给我一点时间' border fit highlight-current-row style='width: 100%'>

      <el-table-column type="selection">
      </el-table-column>
      <el-table-column   type="index" width="60">
      </el-table-column>

      <el-table-column  label='订单号' prop="no" width="150">
      </el-table-column>
      <el-table-column label='地址' show-overflow-tooltip prop="location">
      </el-table-column>
      <el-table-column label='人员' show-overflow-tooltip prop="name">
      </el-table-column>
      <el-table-column label='电话' width="150" prop="tel">
      </el-table-column>
      <el-table-column v-if='showAuditor' align="center" label="总价" prop="total">
      </el-table-column>
      <el-table-column label='状态' align="center" width="100">
        <template scope="scope">
          {{scope.row.enable | enableFilter}}
        </template>
      </el-table-column>
      <el-table-column v-if='showAuditor' width="350" align="left" label="详细">
        <template scope="scope">
          <p v-html="scope.row.detail"></p>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="150">
        <template scope="scope">
          <el-button size="small" type="success" @click="handleUpdate(scope.row)">修改
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div v-show='!listLoading' class='pagination-container'>
      <el-pagination @size-change='handleSizeChange' @current-change='handleCurrentChange' :current-page.sync='listQuery.page'
        :page-sizes='[10,20,30,50]' :page-size='listQuery.limit' layout='total, sizes, prev, pager, next, jumper' :total='total'>
      </el-pagination>
    </div>
    <el-dialog title="汇总" :visible.sync="collectFormVisible">
      <el-table :data='collection' v-loading='collLoading'element-loading-text='给我一点时间' border fit highlight-current-row style='width: 100%'>
        <el-table-column  label='食品' prop="descr" width="150">
        </el-table-column>
        <el-table-column  label='数量' prop="num" width="150">
        </el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog title="更新" :visible.sync="dialogFormVisible">
      <el-form class="small-space" :model="temp" :rules="rules" ref="form" label-position="left" label-width="70px" style='width: 400px; margin-left:50px;'>
        <el-form-item >
          <el-select v-model="temp.enable" label="状态">
            <el-option label="未接收" value="0"></el-option>
            <el-option label="已接收" value="10"></el-option>
            <el-option label="配送中" value="20"></el-option>
            <el-option label="已配送" value="30"></el-option>
            <el-option label="已完成" value="40"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="update">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, update } from "@/api/order";
import { collect } from "@/api/orderDetail";
import { restSel } from "@/api/rest";
import waves from "@/directive/waves/index.js"; // 水波纹指令

export default {
  name: "x",
  directives: {
    waves
  },
  data() {
    return {
      sels: [],
      list: null,
      collection: null,
      showAuditor: false,
      total: 0,
      rests: [],
      listLoading: null,
      collLoading: null,
      listQuery: {
        page: 1,
        limit: 20,
        restId: undefined,
        section: undefined,
        daily: undefined,
        enable: undefined,
        payStatus: "1",
        sort: "+daily"
      },
      dailySech: "2017-01-01",
      temp: {
        id: undefined,
        enable: ""
      },
      dialogFormVisible: false,
      collectFormVisible: false,
      tableKey: 0,
      rules: {
        descr: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" }
        ],
        tel: [{ required: true, message: "请输入活动名称", trigger: "blur" }]
      },
      pickerOptions2: {
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              const end = new Date();
              picker.$emit("pick", [end, end]);
            }
          },
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            }
          }
        ]
      }
    };
  },
  created() {
    // this.getList();
    this.getRests();
  },
  filters: {
    enableFilter: function(value) {
      if ("0" === value) {
        return "未接收";
      } else if ("10" === value) {
        return "已接收";
      } else if ("20" === value) {
        return "配送中";
      } else if ("30" === value) {
        return "已配送";
      } else if ("40" === value) {
        return "已完成";
      }
      return "未知状态";
    }
  },
  methods: {
    getList() {
      this.listLoading = true;
      fetchList(this.listQuery).then(response => {
        // debugger
        this.list = response.data.items;
        this.total = response.data.total;
        this.listLoading = false;
      });
    },
    dailySechChange(val) {
      this.listQuery.daily = val;
    },
    getRests() {
      restSel().then(response => {
        // debugger
        this.rests = response.data.items;
      });
    },
    handleCollect() {
      this.collectFormVisible = true;
      this.collLoading = true;
      collect(this.listQuery).then(response => {
        // debugger
        this.collection = response.data.items;
        this.collLoading = false;
      });
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row);
      this.dialogFormVisible = true;
    },
    selsChange(sels) {
      this.sels = sels;
    },
    update() {
      //TODO 后续改为批量模式
      this.$refs["form"].validate(async valid => {
        if (valid) {
          const res = await update(this.temp);
          console.log(res);
          if (res.data.code == 1) {
            for (const v of this.list) {
              // console.log(this.list)
              // console.log(v)
              if (v.id === this.temp.id) {
                const index = this.list.indexOf(v);
                this.list.splice(index, 1, this.temp);
                break;
              }
            }
            this.$notify({
              title: "成功",
              message: "更新成功",
              type: "success",
              duration: 2000
            });

            console.log(Date.parse(new Date()));
          } else {
            this.$notify({
              title: "失败",
              message: "更新失败",
              type: "error",
              duration: 2000
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
        this.dialogFormVisible = false;
      });
    },
    resetTemp() {
      this.temp = {
        id: undefined
      };
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getList();
    },
    handleDownload() {
      require.ensure([], () => {
        const { export_json_to_excel } = require("vendor/Export2Excel");
        const tHeader = ["ID", "名称", "描述", "地址", "电话"];
        const filterVal = ["id", "descr", "longDescr", "location", "tel"];
        const data = this.formatJson(filterVal, this.list);
        export_json_to_excel(tHeader, data, "table数据");
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === "tel") {
            return "不可下载";
          } else {
            return v[j];
          }
        })
      );
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList();
    }
  }
};
</script>